﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using LView.CMS.IServices;
using LView.CMS.ViewModels;
using SQLBuilder.Core.Repositories;
using LView.CMS.Models;
using System.Linq;

namespace LView.CMS.Services
{
    public class RolePermissionServices : IRolePermissionServices
    {
        private readonly IRepository _repository;
        public RolePermissionServices(Func<string, IRepository> handler)
        {
            _repository = handler(null);
        }

        public async Task<BaseResult> AddOrModifyAsync(string[] menusId, string roleId)
        {
            var result = new BaseResult();
            var roleOriPermission = _repository.FindList<LMSRolePermission>(x => x.RoleId == roleId);
            if (roleOriPermission.Count() > 0)
            {
                roleOriPermission.ToList().ForEach(async x =>
               {
                   await _repository.DeleteAsync<LMSRolePermission>(x);
               });
            }
            try
            {
                await Task.Run(() =>
                {
                    menusId.ToList().ForEach(async x =>
                    {
                        var rolePermission = new LMSRolePermission();
                        rolePermission.Id = Guid.NewGuid().ToString();
                        rolePermission.RoleId = roleId;
                        rolePermission.MenuId = x;
                        await _repository.InsertAsync<LMSRolePermission>(rolePermission);
                    });

                });
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            catch (Exception ex)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg + $":{ex.Message}";
            }
            return result;
        }
    }
}
